package sudoku

import "math/rand"

var size int = 9
var boxSize int = 3

// 创建空白单元格
func EmptyCells() []int {
	return make([]int, 81)
}

// 随机生成一个的完整的单元格
func FullCells() []int {
	cells := EmptyCells()

	for i, v := range rand.Perm(9) {
		index := i*9 + rand.Intn(9)
		cells[index] = v + 1
	}

	count := Solve(cells)
	if count > 0 {
		return cells
	}
	return EmptyCells()
}

// 克隆单元格
func CloneCells(cells []int) []int {
	items := make([]int, len(cells))
	copy(items, cells)
	return items
}

func GetHighlight(cells []int, selected int) map[int]int {
	var result map[int]int

	x := selected % size
	y := int(selected / size)
	b := int(y/boxSize)*boxSize + int(x/boxSize)

	for i := 0; i < size; i++ {
		rowIndex := i + y*size
		result[rowIndex] = cells[rowIndex]

		colIndex := x + i*size
		result[colIndex] = cells[colIndex]
	}

	sx := b % boxSize * boxSize
	sy := int(b/boxSize) * boxSize
	for i := 0; i < boxSize; i++ {
		for j := 0; j < boxSize; j++ {
			boxIndex := sx + i + (sy+j)*size
			result[boxIndex] = cells[boxIndex]
		}
	}

	return result
}

// 验证当前指定单元格填写是否有效
func IsValidCell(cells []int, selected int) bool {

	cellValue := cells[selected]
	if cellValue == 0 {
		return false
	}

	for index, value := range GetHighlight(cells, selected) {
		if index != selected && value == cellValue {
			return false
		}
	}

	return true
}
